import template from './ng-toast.template.html';
import angular from 'angular';

ngToastContainerDirective.$inject = ['ngToastService', '$sce'];

function ngToastContainerDirective(ngToastService, $sce) {
  return {
    restrict: 'E',
    template,
    scope: {
      placement: '@?'
    },
    link: function(scope) {
      scope.placement = scope.placement || 'top-right';
      scope.toasts = ngToastService.toasts;

      scope.closeToast = function(toast) {
        ngToastService.remove(toast.id);
      };

      scope.$watchCollection(function() {
        return ngToastService.toasts;
      }, function(newToasts) {
        scope.toasts = newToasts;

        angular.forEach(newToasts, function(toast) {
          if (toast && toast.message && !toast._trusted) {
            toast.message = $sce.trustAsHtml(toast.message);
            toast._trusted = true;
          }
        });
      });
    }
  };
}

export default ngToastContainerDirective;
